<script setup lang="ts">
import QNav from '@/components/q-nav/q-nav.vue'
import ClassSearch from './components/class-search.vue'
import SlideNav from './components/slide-nav.vue'
import ClassOne from './components/class-one.vue'
import ClassThree from './components/class-three.vue'
import ClassFive from './components/class-five.vue'
import { useStatusBar } from '@/hooks'
import { useSettingStore } from '@/store/modules/setting'
import { doGetEnablePageByType } from '@/apis/decoration/platform'
import { doGetCategoryLevelFromPlatform, doGetCommodityBySecCateIdFromPlatform } from '@/apis/decoration/platform'
import { DeCategoryType, ApiCategoryData } from '@/pages/platform/types'
import { doGetRetrieveCommodity } from '@/apis/good'

// eslint-disable-next-line no-undef
const pages = getCurrentPages()
const { SET_LOADING } = useSettingStore()
// 状态栏高度
const statusBarHeight = useStatusBar()
let headerNodeHeight = uni.upx2px(20)
// #ifndef H5
headerNodeHeight = uni.upx2px(100)
// #endif
// 底部导航安全距离高度
const safeHeight = useBottomSafe()
// 底部导航高度(rpx)
const tabbarNode = uni.upx2px(100)
// 搜索组件高度(rpx)
const searchNode = uni.upx2px(80)
// 分类高度
const classNodeHeight = computed(() => {
  // 屏幕高度
  let height = 0
  // #ifdef H5
  height = useScreenHeight().value - searchNode - tabbarNode - statusBarHeight.value - headerNodeHeight - safeHeight.value
  // #endif
  // #ifndef H5
  height = useScreenHeight().value - searchNode - tabbarNode - statusBarHeight.value - safeHeight.value
  // #endif
  return height
})
// slide-nav的下标
const slideNavIndex = ref(0)
// navTab的下标
const navIndex = ref(0)
// 获取当前分类列表
const currentCategoryInfo = ref<ApiCategoryData>()
// 获取商品列表
const commodityList = ref([])
// 样式2，5商品列表
const commodity2List = ref([])
// 分类页配置
const categoryConfig = ref<DeCategoryType>({
  style: 1,
  listStyle: 1,
  buyBtnStyle: 1,
  goodsMargin: 0,
  fontSelected: '#FF0000',
  bgSelected: '#0E0202',
  fontNotSelected: '#000000',
  bgNotSelected: '#F5F5F5',
  categoryList: [],
})
// 分页信息
const pageConfig = reactive({
  current: 1,
  pages: 1,
  size: 10,
})
const getNextSlideName = computed(() => {
  if (categoryConfig.value.categoryList.length <= slideNavIndex.value + 1) {
    return ''
  } else {
    return categoryConfig.value.categoryList[slideNavIndex.value + 1].platformCategoryFirstName
  }
})
const classThreeRef = ref()
const classOneRef = ref()

initCategoryConfig()

const handleChangeSlideTab = async (e: number) => {
  slideNavIndex.value = e
  // 切换slide初始化数据
  commodityList.value = []
  navIndex.value = 0
  classThreeRef.value && classThreeRef.value.handleBackTop()
  classOneRef.value && classOneRef.value.handleBackTop()
  initPageConfig()
  await initfirstBelowCate()
  if (categoryConfig.value.style === 3 || categoryConfig.value.style === 4) {
    initCommodityBySecId()
  } else if (categoryConfig.value.style === 2 || categoryConfig.value.style === 5) {
    initCommodity2BySecId()
  }
}
const handleChangeNavTab = (e: number) => {
  navIndex.value = e
  initPageConfig()
  initCommodityBySecId()
}
/**
 * 样式34下分页加载商品列表
 */
const handleListLoadMore = () => {
  // 触底加载下个slide内容
  // if (pageConfig.current >= pageConfig.pages && getNextSlideName) {
  //     handleChangeSlideTab(slideNavIndex.value + 1)
  //     return
  // }
  initCommodityBySecId(true)
}
/**
 * 样式25下分页加载商品列表
 */
const handleListLoadMore2 = () => {
  initCommodity2BySecId(true)
}
/**
 * 根据一级分类查询id查询下级分类信息
 */
async function initfirstBelowCate() {
  if (categoryConfig.value?.categoryList?.[slideNavIndex.value]?.platformCategoryFirstId) {
    const { code, data } = await doGetCategoryLevelFromPlatform(
      [categoryConfig.value?.categoryList?.[slideNavIndex.value]?.platformCategoryFirstId],
      'LEVEL_3',
    )
    if (code !== 200)
      return uni.showToast({
        icon: 'none',
        title: '获取分类失败',
      })
    if (data[0]) {
      currentCategoryInfo.value = data[0]
    } else {
      currentCategoryInfo.value = void 0
    }
  }
}
/**
 * 根据二级id查询商品列表
 */
async function initCommodityBySecId(isLoad = false) {
  if (!isLoad) {
    // 刷新
    commodityList.value = await getGoodList()
  } else if (isLoad && pageConfig.current < pageConfig.pages) {
    // 更新
    pageConfig.current++
    commodityList.value = commodityList.value.concat(await getGoodList())
  }
}
async function getGoodList() {
  if (!currentCategoryInfo.value) {
    uni.showToast({
      icon: 'none',
      title: '分类加载失败',
    })
    return []
  }
  const { code, data } = await doGetRetrieveCommodity({
    platformCategorySecondId: currentCategoryInfo.value.children[navIndex.value].id,
    current: pageConfig.current,
    size: pageConfig.size,
  })
  //const { code, data } = await doGetCommodityBySecCateIdFromPlatform(currentCategoryInfo.value.children[navIndex.value].id, 'LEVEL_2', pageConfig)
  if (code !== 200) {
    uni.showToast({
      icon: 'none',
      title: '获取商品失败',
    })
    return []
  }
  pageConfig.pages = data.pages
  return data.list
}
/**
 * 根据二级id查询商品列表
 */
async function initCommodity2BySecId(isLoad = false) {
  if (!isLoad) {
    // 刷新
    commodity2List.value = await getGoodList2()
  } else if (isLoad && pageConfig.current < pageConfig.pages) {
    // 更新
    pageConfig.current++
    commodity2List.value = commodity2List.value.concat(await getGoodList2())
  }
}
async function getGoodList2() {
  if (!currentCategoryInfo.value) {
    uni.showToast({
      icon: 'none',
      title: '分类加载失败',
    })
    return []
  }
  const { code, data } = await doGetRetrieveCommodity({
    platformCategoryFirstId: currentCategoryInfo.value.id,
    current: pageConfig.current,
    size: pageConfig.size,
  })
  if (code !== 200) {
    uni.showToast({
      icon: 'none',
      title: '获取商品失败',
    })
    return []
  }

  pageConfig.pages = data.pages
  return data.list
}
/**
 * 获取分类配置数据
 */
async function initCategoryConfig() {
  // #ifdef MP-WEIXIN
  // @ts-ignore
  const endpointType = 'WECHAT_MINI_APP'
  // #endif
  // #ifndef MP-WEIXIN
  // @ts-ignore
  // eslint-disable-next-line no-redeclare
  const endpointType = 'H5_APP'
  // #endif
  const { code, data } = await doGetEnablePageByType(endpointType, 'PRODUCT_CATEGORY_PAGE')
  if (code !== 200) {
    uni.showToast({
      icon: 'none',
      title: '获取分类配置失败',
    })
    return
  }
  if (!data || !data.properties || JSON.parse(data.properties).length === 0) {
    uni.showToast({
      icon: 'none',
      title: '分类页暂无配置',
    })
    return
  }
  categoryConfig.value = JSON.parse(data.properties)[0].formData
  await initfirstBelowCate()
  if (categoryConfig.value.style === 3 || categoryConfig.value.style === 4) {
    initCommodityBySecId()
  } else if (categoryConfig.value.style === 2 || categoryConfig.value.style === 5) {
    initCommodity2BySecId()
  }
  SET_LOADING(false)
}
/**
 * 初始化分页信息
 */
function initPageConfig() {
  pageConfig.current = 1
  pageConfig.pages = 1
}
</script>

<template>
  <!-- #ifdef APP-PLUS -->
  <q-nav v-if="pages[pages.length - 1].route !== 'pages/modules/classification/classification'" :show-back="false" title="分类" />
  <!-- #endif -->
  <!-- #ifdef MP-WEIXIN -->
  <q-nav v-if="pages[pages.length - 1].route !== 'pages/modules/classification/classification'" :show-back="false" title="" />
  <!-- #endif -->
  <!-- #ifdef H5 -->
  <view v-if="pages[pages.length - 1].route !== 'pages/modules/classification/classification'" style="height: 20rpx; background-color: #fff" />
  <!-- #endif -->
  <class-search />
  <!-- TODO:待完善上拉加载和下拉刷新  -->
  <ClassFive
    v-if="categoryConfig.style === 5"
    :first-cate-list="currentCategoryInfo"
    :current-choose-index="slideNavIndex"
    :list="commodity2List"
    :config="categoryConfig"
    :height="classNodeHeight"
    @change-tab="handleChangeSlideTab"
    @list-load-more="handleListLoadMore2"
  />
  <view v-else class="content">
    <slide-nav :current-choose-index="slideNavIndex" :height="classNodeHeight" :config="categoryConfig" @change-tab="handleChangeSlideTab" />
    <class-one
      v-if="categoryConfig.style === 1 || categoryConfig.style === 2"
      ref="classOneRef"
      :height="classNodeHeight"
      :info="currentCategoryInfo"
      :large="categoryConfig.style"
      :list="commodity2List"
      :page-config="pageConfig"
      @list-load-more="handleListLoadMore2"
    />
    <class-three
      v-else
      ref="classThreeRef"
      :current-choose-index="navIndex"
      :first-cate-list="currentCategoryInfo"
      :height="classNodeHeight"
      :config="categoryConfig"
      :list="commodityList"
      :next-slide-name="getNextSlideName"
      :page-config="pageConfig"
      @list-load-more="handleListLoadMore"
      @change-tab="handleChangeNavTab"
    />
  </view>
</template>

<style lang="scss" scoped>
@include b(content) {
  @include flex();
  background: #fff;
}
</style>
